/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ac.ui;

import ac.settings.dataModelurls;
import ac.settings.rowsStatus;
import ac.ui.controls.PCLCode;
import ac.ui.controls.PCLGetdata;
import ac.ui.controls.PCLGetdataFull;
import ac.ui.controls.PCLTextField;
import ac.ui.controls.PCLcomboboxAdd;
import ac.uitls.data;
import java.awt.Color;
import java.awt.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 * the parent class that encapsulates all windows operations.
 * @author empcl_000
 */
public class FrameOpertion implements dataModelurls, rowsStatus {

    public int IndexID = 0;

    public int actionStatus = 0;

    public String TabelString;

    public String[] dataSaveFields;
    public String[] dataSaveValues;

    /**
     * 1-start With Id;<br>
     * pattern dataType_DataWidth ;<br>
     * Types Like addsTreeID,addsID,;<br>
     * sizes minWidth,midWidth,maxWidth,hide; <br>* like "id_", "_hide",
     * "_maxWadth", "_midWidth", "_midWidth", "addsID_midWidth", "_midWidth",
     * "addsTreeID_midWidth", "_hide", "_hide"<br>
     *
     */
    public String[] dataViewAS = null;

    public String[] dataSaveAs = null;
    public Component[] dataComponents;

    public String[] useDataFilesTypes = null;

    public String indexTitle;
    public String indexField;
    public String indexviewAs = "";
    public JTable index;
    public JTable serachTabel;
    public JTable deleteTabel;
    public JPanel[] panels;
    public String Where = "";

    public JTable reportIndex;
    public boolean sendMessage = true;

    public Map<String, Component> ActionsButtons = new HashMap<String, Component>();

    ac.uitls.propertiesOperation op = new ac.uitls.propertiesOperation();
    ac.ui.utils u = new ac.ui.utils();
    protected ac.lib.database.operations db = new ac.lib.database.operations();
    public data d = new data();

    //<editor-fold defaultstate="collapsed" desc="Update Data">
    public void indexUpdate() {
        d.Indexupdate(index, TabelString, indexField, "id", indexTitle, Where, indexviewAs);
    }

    public void indexRepIndex() {
        d.Indexupdate(reportIndex, TabelString, indexField, "id", indexTitle, Where, indexviewAs);
    }

    public void indexsearch() {
        d.Indexupdate(serachTabel, TabelString, dataSaveFields, Where, dataViewAS);
    }

    public void indexdelete() {

        d.withOutData = true;
        d.Indexupdate(deleteTabel, TabelString, dataSaveFields, "rowstatus='" + rowDeleted + "'", dataViewAS);
        d.withOutData = false;
    }

    public void indexsearch(String sqlquery) {

        d.Indexupdate(serachTabel, sqlquery, dataViewAS);

    }

    private String updatToSqData() {
        String data = "";
        int i = 0;
        for (String v : dataSaveFields) {
            if (i == 0) {
                data += "`" + v + "`";
            } else {
                data += ",`" + v + "`";
            }

            i = 1;
        }
        return data;

    }

    public String FrameDataUpdateFromSearch() {

        IndexID = Integer.parseInt(d.IndexGetValue(serachTabel));
        if (index != null) {
            d.IndexsetValue(index, "" + IndexID);
        }
        return FrameDataupdate();

    }

    public void addprintTemp(String file, String Query) {

        ac.reportes.reportes r = new ac.reportes.reportes();
        r.tabel = TabelString;
        r.Name = TabelString + "_file_print";
        r.where = "`id`='" + IndexID + "'";
        r.craeteReporte();
        r.showReport(file);

    }

    public void addprintTemp(String file) {

        ac.reportes.reportes r = new ac.reportes.reportes();
        r.tabel = TabelString;
        r.Name = TabelString + "_file_print";
        r.where = "`id`='" + IndexID + "'";
        r.craeteReporte();
        r.showReport(file);

    }

    public String FrameDataupdate() {

        IndexID = Integer.parseInt(d.IndexGetValue(index));
        String[] dataString = db.getRow(TabelString, updatToSqData(), IndexID);

        String test = db.retuensqlString;
        test += db.retuenErrorMessage;
        test += db.retuenstatus;
        u.DataToComponents(dataComponents, IndexID, dataString, dataSaveFields, TabelString, dataSaveAs);
        return (index.getSelectedRow() + 1) + "/" + index.getRowCount();
    }

    public String FrameDataupdate(String indexselection) {
        clerPanels(true);

        String returnData = "";
        int go = 0;
        switch (indexselection) {

            case "frist":

                returnData = FrameDataupdate(0);
                break;
            case "next":

                go = index.getSelectedRow() + 1;
                if (go > index.getRowCount() - 1) {
                    go = 0;
                }
                returnData = FrameDataupdate(go);

                break;
            case "perv":
                go = index.getSelectedRow() - 1;
                if (go < 0) {
                    go = index.getRowCount() - 1;
                }

                returnData = FrameDataupdate(go);
                break;

            case "last":

                returnData = FrameDataupdate(index.getRowCount() - 1);
                break;
        }
        return returnData;

    }

    public void FrameDataupdateByid(int IndexID) {

        String[] dataString = db.getRow(TabelString, updatToSqData(), IndexID);

        String test = db.retuensqlString;
        test += db.retuenErrorMessage;
        test += db.retuenstatus;

        u.DataToComponents(dataComponents, IndexID, dataString, dataSaveFields, TabelString, dataSaveAs);

    }

    public String FrameDataupdate(int indexselection) {
        String re = "";
        try {
            // if (IndexID > 0) {
            if (index != null) {

                // if (IndexID > 0) {
                index.getSelectionModel().setSelectionInterval(indexselection, indexselection);
                index.repaint();
                IndexID = Integer.parseInt(d.IndexGetValue(index));
                re = (index.getSelectedRow() + 1) + "/" + index.getRowCount();
                //  }
            } else {
                IndexID = indexselection;
            }
            FrameDataupdateByid(IndexID);

            //  }
        } catch (Exception e) {
            //  ac.ui.utils.sendError(index, "X", e.getMessage());
        }

        return re;

    }
//</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Components">
    public boolean chackReq() {
        boolean r = true;

        if (dataComponents != null) {
            for (Component c : dataComponents) {
                if (c instanceof PCLTextField) {

                    PCLTextField d = (PCLTextField) c;
                    if (d.isRequired()) {

                        String v = d.getText();
                        if (v == null || v.equalsIgnoreCase("")) {
                            r = false;

                        }

                    }
                } else if (c instanceof PCLCode) {

                    PCLCode d = (PCLCode) c;
                    if (d.isRequired()) {

                        String v = d.getText();
                        if (v == null || v.equalsIgnoreCase("")) {
                            r = false;

                        }

                    }
                } else if (c instanceof PCLGetdata) {

                    PCLGetdata d = (PCLGetdata) c;
                    if (d.isRequired()) {
                        String v = ac.ui.utils.comBoxGetValue(d);

                        if (v == null || v.equalsIgnoreCase("")) {
                            r = false;

                        }

                    }

                } else if (c instanceof PCLcomboboxAdd) {

                    PCLcomboboxAdd d = (PCLcomboboxAdd) c;
                    if (d.isRequired()) {
                        String v = ac.ui.utils.comBoxGetValue(d);

                        if (v == null || v.equalsIgnoreCase("")) {
                            r = false;

                        }

                    }

                } else if (c instanceof PCLGetdataFull) {

                    PCLGetdataFull d = (PCLGetdataFull) c;
                    if (d.isRequired()) {
                        String v = ac.ui.utils.comBoxGetValue(d);

                        if (v == null || v.equalsIgnoreCase("")) {
                            r = false;

                        }

                    }

                }
            }
        }
        if (!r) {

            utils.sendRequiredNeedeMssage(null);
        }

        return r;
    }

    public void clerPanels(boolean stat) {
        if (panels != null) {

            for (JPanel p : panels) {
                u.panelClaer(p.getComponents(), stat);
            }
        }

    }

    public void EnablePanels(boolean stat) {
        if (panels != null) {

            for (JPanel p : panels) {
                ac.ui.utils.ComponentsEnable(p.getComponents(), stat);
            }
        }

    }

    public void mapsBtsActions(boolean Status) {
        if (ActionsButtons.size() > 0) {
            Set mapSet = (Set) ActionsButtons.entrySet();
            //Create iterator on Set
            Iterator mapIterator = mapSet.iterator();

            while (mapIterator.hasNext()) {
                Map.Entry mapEntry = (Map.Entry) mapIterator.next();
                // getKey Method of HashMap access a key of map
                // JButton keyValue = (JButton) mapEntry.getKey();
                //getValue method returns corresponding key's value
                JButton value = (JButton) mapEntry.getValue();

                value.setEnabled(Status);

            }
        }
    }
//</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Add Data">
    public void addStep1() {
        JButton addBt = (JButton) ActionsButtons.get("add");
        clerPanels(true);

        mapsBtsActions(false);
        addBt.setEnabled(true);
        EnablePanels(true);
        addBt.setText(op.getWord("label.save"));
        actionStatus = 1;
        dataComponents[0].requestFocus();
    }

    public int addStep2(boolean add, boolean statusEnableAfter, boolean clear) {
        JButton addBt = (JButton) ActionsButtons.get("add");

        int addStatus = 0;
        if (add == true && chackReq()) {

            if (useDataFilesTypes == null) {

                String[][] data = {dataSaveFields, dataSaveValues};
                db.setInsert(TabelString, data);

            } else {

                db.insertV2(TabelString, dataSaveFields, dataSaveValues, useDataFilesTypes);
            }

            String test = db.retuenErrorMessage;

            test += db.retuensqlString;
            if (db.retuenstatus > 0) {

                addStatus = db.retuenstatus;
                if (sendMessage) {
                    utils.sendSaveMssage(addBt);
                }
                if (addBt != null) {
                    addBt.setText(op.getWord("label.add"));
                }
                // System.out.println(test);
                actionStatus = 0;
                mapsBtsActions(true);
                if (clear) {
                    clerPanels(true);
                }

                EnablePanels(statusEnableAfter);
            } else {

                utils.sendSaveErrorMssage(addBt);
            }

        }
        return addStatus;
    }

    public void addnewTemp(boolean add, boolean statusEnableAfter) {

        if (actionStatus == 0) {
            addStep1();

        } else {
            addStep2(add, statusEnableAfter, true);
        }

    }

    public int addnewTempr(boolean add, boolean statusEnableAfter, boolean clear) {

        int addStatus = 0;

        if (actionStatus == 0) {
            addStep1();
        } else {
            addStatus = addStep2(add, statusEnableAfter, clear);
        }

        return addStatus;
    }

//</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Edit">
    public void editStep1() {
        JButton editBt = (JButton) ActionsButtons.get("edit");
        mapsBtsActions(false);
        editBt.setEnabled(true);
        EnablePanels(true);
        editBt.setText(op.getWord("label.save"));
        actionStatus = 1;

    }

    public int editStep2(boolean add, boolean statusEnableAfter) {

        int returnS = 0;
        JButton editBt = (JButton) ActionsButtons.get("edit");
        if (add == true && chackReq()) {

            if (useDataFilesTypes == null) {
                String[][] data = {dataSaveFields, dataSaveValues};

                db.setUpdate(TabelString, data, IndexID);
            } else {
                db.setUpdatev2(TabelString, dataSaveFields, dataSaveValues, useDataFilesTypes, IndexID);

            }
            returnS = db.retuenstatus;
            String test = db.retuenErrorMessage;
            test += db.retuensqlString;
            if (db.retuenstatus > 0) {

                editBt.setText(op.getWord("label.edit"));
                if (sendMessage) {
                    utils.sendUpdateMssage(editBt);
                }
                actionStatus = 0;
                mapsBtsActions(true);
                EnablePanels(statusEnableAfter);

            } else {
                utils.sendUpdateeErrorMssage(editBt);

            }
        }
        return returnS;
    }

    public int addEditTemp(boolean add, boolean statusEnableAfter) {
        int r = 0;
        if (actionStatus == 0) {
            editStep1();
        } else {
            r = editStep2(add, statusEnableAfter);
        }
        return r;

    }
//</editor-fold>

    public String setcancel() {

        String r = "";
        if (IndexID == 0) {
            r = FrameDataupdate("frist");
        } else {
            r = FrameDataupdate(IndexID);

        }

        JButton addBt = (JButton) ActionsButtons.get("add");
        addBt.setText(op.getWord("label.add"));

        JButton editBt = (JButton) ActionsButtons.get("edit");
        editBt.setText(op.getWord("label.edit"));

        mapsBtsActions(true);

        actionStatus = 0;
        return r;
    }

    public String setcancel(boolean EnablePanels, boolean updateForm) {

        String r = "";
        if (IndexID == 0) {
            r = FrameDataupdate("frist");
        } else {
            r = FrameDataupdate(IndexID);

        }

        JButton addBt = (JButton) ActionsButtons.get("add");
        addBt.setText(op.getWord("label.add"));

        JButton editBt = (JButton) ActionsButtons.get("edit");
        editBt.setText(op.getWord("label.edit"));

        mapsBtsActions(true);

        EnablePanels(EnablePanels);
        actionStatus = 0;
        return r;
    }

    public String setcancel(boolean updateForm) {
        String r = "";
        if (updateForm) {

            if (IndexID == 0) {
                r = FrameDataupdate("frist");
            } else {
                r = FrameDataupdate(IndexID);

            }
        }
        JButton addBt = (JButton) ActionsButtons.get("add");
        addBt.setText(op.getWord("label.add"));

        JButton editBt = (JButton) ActionsButtons.get("edit");
        editBt.setText(op.getWord("label.edit"));

        mapsBtsActions(true);
        actionStatus = 0;
        return r;
    }

    public int addDeletTemp(boolean add, String where) {

        if (add == true) {
            db.retuenstatus = 0;
            if (utils.sendDeleteMssage(ActionsButtons.get("delete")) == 0) {

                // db.setDelete(TabelString, where);
                setDelete(where);

                if (db.retuenstatus == 1) {

                    utils.sendDeleteDoneMssage(ActionsButtons.get("delete"));
                } else {
                    utils.sendDeleteErrorMssage(ActionsButtons.get("delete"));
                }
                String test = db.retuenErrorMessage;
                test += db.retuensqlString;
            }
        }
        return db.retuenstatus;

    }

    public int addDeletTemp(boolean add) {

        if (add == true) {
            db.retuenstatus = 0;
            if (utils.sendDeleteMssage(ActionsButtons.get("delete")) == 0) {

                // db.setDelete(TabelString, IndexID);
                setDelete(IndexID);

                if (db.retuenstatus == 1) {

                    utils.sendDeleteDoneMssage(ActionsButtons.get("delete"));
                } else {
                    utils.sendDeleteErrorMssage(ActionsButtons.get("delete"));
                }
                String test = db.retuenErrorMessage;
                test += db.retuensqlString;
            }
        }
        return db.retuenstatus;

    }

    int setDelete(String where) {

        db.retuenstatus = 0;
        String[][] data = {{"rowstatus"}, {rowDeleted}};

        db.setUpdate(TabelString, data, where);

        return db.retuenstatus;

    }

    int setDelete(int id) {
        db.retuenstatus = 0;
        String[][] data = {{"rowstatus"}, {rowDeleted}};

        db.setUpdate(TabelString, data, id);

        return db.retuenstatus;

    }

    public int setRestore(int id) {
        db.retuenstatus = 0;
        String[][] data = {{"rowstatus"}, {rowNormal}};

        db.setUpdate(TabelString, data, id);

        return db.retuenstatus;

    }

    public int setRestoreAll() {

        db.retuenstatus = 0;

        String[][] data = {{"rowstatus"}, {rowNormal}};

        db.setUpdate(TabelString, data, "1=1");

        return db.retuenstatus;

    }

    public int setRemove(int id) {
        int status = 0;

        if (utils.sendRemoveMssage(null) == 0) {
            db.setDelete(TabelString, id);
            status = 1;
        }
        return status;
    }

    public int setRemoveAll() {
        if (utils.sendRemoveAllMssage(null) == 0) {
            db.setDelete(TabelString, "rowstatus='" + rowDeleted + "'");
        }
        return db.retuenstatus;
    }

    public int setRemoveAllRestore() {
        db.setDelete(TabelString, "rowstatus='" + rowRestore + "'");
        return db.retuenstatus;
    }

}
